package com.example.aicloud.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security框架配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Resource
    LoginAuthenticationFilter loginAuthenticationFilter;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return  new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .httpBasic(AbstractHttpConfigurer::disable) //禁用明文验证
                .csrf(AbstractHttpConfigurer::disable) //禁用csrf验证
                .formLogin(AbstractHttpConfigurer::disable) //禁用默认登录页面
                .logout(AbstractHttpConfigurer::disable) // 禁用默认退出页面
                .headers(AbstractHttpConfigurer::disable) // 禁用默认的header（支持 iframe 访问页面）
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) //禁用session，因为项目使用了JWT认证
                .authorizeHttpRequests(auth -> auth.requestMatchers(  //放行静态资源
                        "/layui/**",
                        "/login.html",
                        "/index.html",
                        "/register.html",
                        "/user/login",
                        "/user/register",
                        "/captcha/create",
                        "/js/**",
                        "/css/**",
                        "/discuss/detail"
                ).permitAll()
                        .anyRequest().authenticated() //其他请求都需要认证
                )
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) //将自定义的 LoginAuthenticationFilter 过滤器插入到 Spring Security 的过滤器链中，并且将其放置在UsernamePasswordAuthenticationFilter 之前。这样可以确保在进行用户名密码认证之前，先通过 JWT 验证用户身份。
                .build();
    }
}
